package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;

    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    @Override
    public PageResult page(CategoryPageQueryDTO categoryPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        //查询数据
        List page = categoryMapper.page(categoryPageQueryDTO.getName(), categoryPageQueryDTO.getType());
        Page pageResult = (Page) page;
        //封装返回
        return new PageResult(pageResult.getTotal(), pageResult.getResult());
    }

    @Override
    public void permission(Integer status, Long id) { //分类启用/禁用
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        categoryMapper.update(category);

    }

    @Override
    public List get(Integer type) {           //分类查询（根据类型）
        return categoryMapper.get(type);
    }

    @Override
    public void save(CategoryDTO categoryDTO) {   //分类新增
        //补全信息
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setStatus(StatusConstant.DISABLE);
        categoryMapper.insert(category);


    }

    @Override
    public void delete(Long id) {
        //查询此分类是否关联菜品，如果关联则抛出异常
        int count = dishMapper.countByCategoryId(id);
        if (count > 0) {
            //当前分类关联了菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        //查询此分类是否关联了套餐，如果关联则抛出异常
        count = setmealMapper.countByCategoryId(id);
        if (count > 0) {
            //当前分类关联了套餐，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //分类信息删除
        categoryMapper.delete(id);
    }

    //根据分类Id查询
    @Override
    public Category getById(Long categoryId) {
        return categoryMapper.getById(categoryId);
    }
}
